package com.atguigu.tingshu.search.service.impl;

import com.atguigu.tingshu.album.client.AlbumInfoFeignClient;
import com.atguigu.tingshu.album.client.CategoryFeignClient;
import com.atguigu.tingshu.model.album.AlbumInfo;
import com.atguigu.tingshu.model.album.BaseCategoryView;
import com.atguigu.tingshu.search.service.ItemService;
import com.atguigu.tingshu.user.client.UserInfoFeignClient;
import com.atguigu.tingshu.vo.album.AlbumInfoDetailVo;
import com.atguigu.tingshu.vo.album.AlbumStatVo;
import com.atguigu.tingshu.vo.user.UserInfoVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.concurrent.*;

@Slf4j
@Service
@SuppressWarnings({"unchecked", "rawtypes"})
public class ItemServiceImpl implements ItemService {

    @Autowired
    private AlbumInfoFeignClient albumInfoFeignClient;
    @Autowired
    private CategoryFeignClient categoryFeignClient;
    @Autowired
    private UserInfoFeignClient userInfoFeignClient;

    //创建线程池对象
    private static final ThreadPoolExecutor threadPoolExecutor = new ThreadPoolExecutor(
            16,
            30,
            60,
            TimeUnit.SECONDS,
            new ArrayBlockingQueue<>(100),
            Executors.defaultThreadFactory(),
            new ThreadPoolExecutor.AbortPolicy()
    );


    /**
     * 获取专辑详情
     *
     * @param albumId
     * @return
     */
    @Override
    public AlbumInfoDetailVo getItem(Long albumId) {

        AlbumInfoDetailVo albumInfoDetailVo = new AlbumInfoDetailVo();

        CompletableFuture<AlbumInfo> f1 = CompletableFuture.supplyAsync(() -> {
            //远程调用获取专辑基本数据
            AlbumInfo albumInfo = albumInfoFeignClient.getAlbumInfo(albumId).getData();
            albumInfoDetailVo.setAlbumInfo(albumInfo);
            return albumInfo;
        }, threadPoolExecutor);

        CompletableFuture<Void> f2 = CompletableFuture.runAsync(() -> {
            //远程调用获取专辑统计数据
            AlbumStatVo albumStatVo = albumInfoFeignClient.getAlbumStatByAlbumId(albumId).getData();
            albumInfoDetailVo.setAlbumStatVo(albumStatVo);
        }, threadPoolExecutor);


        CompletableFuture<Void> f3 = f1.thenAcceptAsync(albumInfo -> {
            //远程调用获取专辑分类数据
            BaseCategoryView baseCategoryView = categoryFeignClient.getByCategory3Id(albumInfo.getCategory3Id()).getData();
            albumInfoDetailVo.setBaseCategoryView(baseCategoryView);
        }, threadPoolExecutor);

        CompletableFuture<Void> f4 = f1.thenAcceptAsync(albumInfo -> {
            //远程调用获取专辑 announcer
            UserInfoVo userInfoVo = userInfoFeignClient.getUserInfo(albumInfo.getUserId()).getData();
            albumInfoDetailVo.setAnnouncer(userInfoVo);
        }, threadPoolExecutor);

        CompletableFuture.allOf(f1, f2, f3,f4).join();
        return albumInfoDetailVo;
    }
}
